package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.security.util.JwtUtils;
import com.example.demo.service.*;
import com.example.demo.utils.SendSms;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.ls.LSInput;

import javax.annotation.Resource;
import javax.swing.text.StyledEditorKit;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;


@Api(tags="商家管理接口")
@RestController
@RequestMapping("/business")
//@CrossOrigin(origins = "*")
public class BusinessController {
    @Resource
    private BusinessService businessService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private MenuMapper menuMapper;

    @Resource
    private AwardService awardService;

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private LogisticsMapper logisticsMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private PrizeService prizeService;

    //注册
//testOK
    @ApiOperation(value ="商家注册")
    @PostMapping("register")
    public Result register(@RequestBody Business business){
        int res = businessService.register(business);
            if(res == 1){
                return Result.success(business);
            }else{
                return Result.error("401","该手机号码已注册");
            }
    }

    //testOK
    //商家登录
//    @ApiOperation(value ="商家登录")
//    @PostMapping("login")
//    public Result login(@RequestBody Business business){
//        Business res = businessService.login(business);
//        Map<String,String> payload=new HashMap<>();
//        payload.put("id",res.getBusinessId().toString());
//        payload.put("name",res.getBusinessName());
//        String token= JwtUtils.createToken(payload);
//        Result result=new Result();
//        result.setCode("200");
//        result.setToken(token);
//        result.setMsg("登录成功");
//        result.setData(res);
//        if(res != null){
//            return result;
//        }else{
//            return Result.error("401","登录失败");
//        }
//    }

    //商家登录
    @ApiOperation(value ="商家退出")
    @PostMapping("logout")
    public Result logout(){
        return Result.success("退出成功");
    }

    //发送短
    @ApiOperation(value ="发送短信")
    @ApiImplicitParam(name = "businessPhone",value = "商家手机",required = true)
    @GetMapping("sendSms")
    public Result sendSms(String businessPhone){
        String code=SendSms.send(businessPhone);
        if(code!=""){
            return Result.success(code);
        }else {
            return Result.error("500", "发送短信失败");
        }
    }

    //testOK
    @ApiOperation(value ="重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessPhone",value = "商家手机",required = true,paramType = "query"),
            @ApiImplicitParam(name = "newPassword",value = "商家新密码",required = true,paramType = "query")
    })
    @PostMapping("reset")
    public Result reset(String businessPhone, String newPassword){
        int result = businessService.reset(businessPhone,newPassword);
        if(result != 0){
            return Result.success("重置密码成功");
        }else{
            return Result.error("401","修改失败");
        }
    }

    //testOK
    @PreAuthorize("hasAuthority('sys:good:add')")
    @ApiOperation(value ="添加商品")
    @PostMapping("addCommodity")
    public Result addCommodity(@RequestBody Goods good){
        int result = goodsService.addCommodity(good);
        if(result != 0){
            return Result.success("添加商品成功");
        }else{
            return Result.error("401","添加失败");
        }
    }

    //testOK
    @PreAuthorize("hasAuthority('sys:good:del')")
    @ApiOperation(value ="删除商品")
    @PostMapping("delCommodity")
    public Result delCommodity(@RequestBody MyArray goodId){
        int result=goodsService.delCommodity(goodId);
        if(result != 0){
            return Result.success("删除成功");
        }else{
            return Result.error("401","查询不到商品信息，删除失败");
        }
    }

    //testOK

    @PreAuthorize(("hasAythority('sys:good:get')"))
    @ApiOperation(value ="获取商品信息")
    @ApiImplicitParam(name = "businessId",value = "商家ID",required = true,paramType = "query")
    @PostMapping("getCommodity")
    public Result getCommodity(int businessId){
        List<Goods> result = goodsService.getCommodity(businessId);
        if(result != null){
            return Result.success(result);
        }else{
            return Result.error("401","查询失败,无商品信息");
        }
    }

    //testOK
    @PreAuthorize("hasAuthority('sys:good:edit')")
    @ApiOperation(value ="修改商品信息")
    @PostMapping("editCommodity")
    public Result editCommodity(@RequestBody Goods good){
        int result = goodsService.editCommodity(good);
        if(result != 0){
            return Result.success("修改商品信息成功");
        }else{
            return Result.error("401","修改商品信息失败");
        }
    }

    //testOK

    @PreAuthorize("hasAuthority('sys:business:edit')")
    @ApiOperation(value ="修改商家信息")
    @PostMapping("editBusiness")
    public Result editBusiness(@RequestBody Business business){
        int result = businessService.editBusiness(business);
        if(result != 0){
            return Result.success("修改商家信息成功");
        }else{
            return Result.error("401","修改商家信息失败");
        }
    }

    //testOK
//    ////@PreAuthorize("hasRole('ROLE_admin')")

//    @PreAuthorize("hasAuthority('sys:business:get')")
    @ApiOperation(value ="获取商家信息")
    @ApiImplicitParam(name = "businessId",value = "商家ID",required = true,paramType = "query",dataType = "int")
    @GetMapping("getBusiness")
    public Result getBusiness(int businessId){
        Business res=businessService.getBusinessById(businessId);
        if(res!=null){
            return Result.success(res);
        }else{
            return Result.error("401","获取商家信息失败");
        }
    }

//    ////@PreAuthorize("hasRole('admin')")

    //testOK

    //@PreAuthorize("hasAuthority('sys:good:get')")
//    @ApiOperation(value = "获取商品列表")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "commodityName", value = "商品名称", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "minPrice", value = "最小价格", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "maxPrice", value = "最大价格", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "int", paramType = "query"),
//            @ApiImplicitParam(name = "current", value = "当前页数", dataType = "int", paramType = "query")
//    })
//    @ApiResponses(value = {
//            @ApiResponse(code = 200, message = "成功"),
//            @ApiResponse(code = 400, message = "参数错误"),
//            @ApiResponse(code = 500, message = "服务器错误")
//    })
//    @GetMapping("getCommodities")
//    public PageInfo<Goods> getCommodities(String commodityName, String minPrice, String maxPrice,
//                                          @RequestParam(defaultValue = "1") int current,
//                                          @RequestParam(defaultValue = "10") int size){
//        List<Goods> goodsList = goodsService.getCommodities();
//
//        Predicate<Goods> predicate = null;
//        if (!commodityName.isEmpty() && minPrice.isEmpty() && maxPrice.isEmpty()) {//name不为空
//            current = 1;
//            predicate = goods -> goods.getGoodName().contains(commodityName);
//        }
//        else if(!commodityName.isEmpty() && !minPrice.isEmpty() && maxPrice.isEmpty()) {//name不为空 min不为空
//            predicate = goods -> goods.getGoodName().contains(commodityName) &&
//                    goods.getGoodPrice() >= Integer.parseInt(minPrice);
//            current = 1;
//        }
//        else if(!commodityName.isEmpty() && !minPrice.isEmpty() && !maxPrice.isEmpty()) {//三个都不为空
//            current = 1;
//            predicate = goods -> goods.getGoodName().contains(commodityName) &&
//                    goods.getGoodPrice() >= Integer.parseInt(minPrice) && goods.getGoodPrice() <= Integer.parseInt(maxPrice);
//        }
//        else if(commodityName.isEmpty() && !minPrice.isEmpty() && maxPrice.isEmpty()){//只有min不为空
//            predicate = goods -> goods.getGoodPrice() >= Integer.parseInt(minPrice);
//            current = 1;
//        }
//        else if(commodityName.isEmpty() && !minPrice.isEmpty() && !maxPrice.isEmpty()){//价格不为空
//            current = 1;
//            predicate = goods -> goods.getGoodPrice() >= Integer.parseInt(minPrice) && goods.getGoodPrice() <= Integer.parseInt(maxPrice);
//        }
//        else if(!commodityName.isEmpty() && minPrice.isEmpty() && !maxPrice.isEmpty()){//name和最大不为空
//            current = 1;
//            predicate = goods -> goods.getGoodName().contains(commodityName) &&
//                    goods.getGoodPrice() <= Integer.parseInt(maxPrice);
//        }
//        else if(commodityName.isEmpty() && minPrice.isEmpty() && !maxPrice.isEmpty()){
//            current = 1;
//            predicate = goods -> goods.getGoodPrice() <= Integer.parseInt(maxPrice);
//        }
//        List<Goods> result = goodsList.stream()
//                .filter(predicate)
//                .collect(Collectors.toList());
//
//        List<Goods> pageList = result.stream()
//                .skip((current - 1) * size) // 跳过前面的记录
//                .limit(size) // 取出指定数量的记录
//                .collect(Collectors.toList()); // 将结果转换为列表
//        PageInfo<Goods> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
//        long total = result.size();
//        pageInfo. setTotal(total);
//        return pageInfo;
//    }

    //testOK

    @PreAuthorize("hasAuthority('sys:good:get')")
    @ApiOperation(value = "根据商家ID获取商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessId", value = "商家ID", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页数", dataType = "int", paramType = "query")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @GetMapping("getCommoditiesByBusinessId")
    public PageInfo<Goods> getCommoditiesByBusinessId(String commodityName, String minPrice, String maxPrice, Integer businessId,
                                                      @RequestParam(defaultValue = "1") int current,
                                                      @RequestParam(defaultValue = "10") int size){
        List<Goods> goodsList = goodsService.getCommodity(businessId);
        Predicate<Goods> predicate = null;
        if (!commodityName.isEmpty() && minPrice.isEmpty() && maxPrice.isEmpty()) {//name不为空
            current = 1;
            predicate = goods -> goods.getGoodName().contains(commodityName);
        } 
        else if(!commodityName.isEmpty() && !minPrice.isEmpty() && maxPrice.isEmpty()) {//name不为空 min不为空
            predicate = goods -> goods.getGoodName().contains(commodityName) &&
                    goods.getGoodPrice() >= Integer.parseInt(minPrice);
            current = 1;
        }
        else if(!commodityName.isEmpty() && !minPrice.isEmpty() && !maxPrice.isEmpty()) {//三个都不为空
            current = 1;
            predicate = goods -> goods.getGoodName().contains(commodityName) &&
                    goods.getGoodPrice() >= Integer.parseInt(minPrice) && goods.getGoodPrice() <= Integer.parseInt(maxPrice);
        }
        else if(commodityName.isEmpty() && !minPrice.isEmpty() && maxPrice.isEmpty()){//只有min不为空
            predicate = goods -> goods.getGoodPrice() >= Integer.parseInt(minPrice);
            current = 1;
        }
        else if(commodityName.isEmpty() && !minPrice.isEmpty() && !maxPrice.isEmpty()){//价格不为空
            current = 1;
            predicate = goods -> goods.getGoodPrice() >= Integer.parseInt(minPrice) && goods.getGoodPrice() <= Integer.parseInt(maxPrice);
        }
        else if(!commodityName.isEmpty() && minPrice.isEmpty() && !maxPrice.isEmpty()){//name和最大不为空
            current = 1;
            predicate = goods -> goods.getGoodName().contains(commodityName) &&
                    goods.getGoodPrice() <= Integer.parseInt(maxPrice);
        }
        else if(commodityName.isEmpty() && minPrice.isEmpty() && !maxPrice.isEmpty()){
            current = 1;
            predicate = goods -> goods.getGoodPrice() <= Integer.parseInt(maxPrice);
        }
        else{
            List<Goods> pageList = goodsList.stream()
                    .skip((current - 1) * size) // 跳过前面的记录
                    .limit(size) // 取出指定数量的记录
                    .collect(Collectors.toList()); // 将结果转换为列表
            PageInfo<Goods> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
            long total = goodsList.size();
            pageInfo. setTotal(total);
            return pageInfo;
        }
        List<Goods> result = goodsList.stream()
                .filter(predicate)
                .collect(Collectors.toList());

        List<Goods> pageList = result.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<Goods> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = result.size();
        pageInfo. setTotal(total);
        return pageInfo;
    }
    
    
    //testOK
    @PreAuthorize("hasAuthority('sys:good:get')")
    @ApiOperation(value = "根据商品ID获取商品信息")
    @ApiImplicitParam(name = "goodId", value = "商品ID", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 402, message = "未能获取商品信息"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @GetMapping("getCommodityById")
    public Result getCommodityById(Integer goodId){
        Goods good=goodsService.getGoodById(goodId);
        if(good!=null){
            return Result.success(good);
        }else{
            return Result.error("402","未能获取商品信息");
        }
    }

    //testOK
    //获取店铺列表
    @PreAuthorize("hasAuthority('sys:business:get')")
    @ApiOperation(value="获取商家列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessName", value = "商家名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "businessPhone", value = "商家手机", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "businessRepres", value = "营业代表人", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页数", dataType = "int", paramType = "query")
    })
    @ApiResponses(value={
            @ApiResponse(code=200, message="成功"),
            @ApiResponse(code=401, message="获取商家列表失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/getBusinessList")
    public PageInfo<Business> getBusinessList(String businessName, String businessPhone,String businessRepres,
                                              @RequestParam(defaultValue = "1") int current,
                                              @RequestParam(defaultValue = "10") int size){
        List<Business> businessList = businessService.getBusinessList();

        if (!businessName.isEmpty() || !businessPhone.isEmpty()||!businessRepres.isEmpty()) {
            current = 1;
        }
        Predicate<Business> predicate = business -> business.getBusinessName().contains(businessName)&&
                                         business.getBusinessPhone().contains(businessPhone)&&
                business.getBusinessRepres().contains(businessRepres) ;//设置过滤条件

        List<Business> result = businessList.stream()
                .filter(predicate)
                .collect(Collectors.toList());

        List<Business> pageList = result.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<Business> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = result.size();
        pageInfo. setTotal(total);
        return pageInfo;
    }

    //删除商家接口

//    ////@PreAuthorize("hasRole('admin')")
    ///testOK
    @PreAuthorize("hasAuthority('sys:business:del')")
    @ApiOperation(value="删除商家", notes="根据商家ID批量删除商家")
    @ApiImplicitParam(name = "ids", value = "商家ID数组", required = true, dataType = "MyArray", paramType = "body")
    @ApiResponses(value={
            @ApiResponse(code=200, message="删除成功"),
            @ApiResponse(code=401, message="删除失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PostMapping("/delBusiness")
    public Result delBusiness(@RequestBody MyArray ids){
        int res=businessService.delBusiness(ids);
        if(res==1){
            return Result.success("删除成功");
        }else{
            return Result.error("401","删除失败");
        }
    }

    //testOK

    @ApiOperation(value="获取菜单列表", notes="根据角色查询菜单列表")
    @ApiImplicitParam(name = "role", value = "角色", dataType = "String", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="成功"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/menu")
    public Result menu(String role){
        QueryWrapper<Menu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role",role);
        List<Menu> menu=menuMapper.selectList(queryWrapper);
        ArrayList<Map<String, Object>> list=new ArrayList<>();
        for(Menu item:menu){
            Map<String,Object> map=new HashMap<>();
            map.put("title",item.getMenuTitle());
            map.put("path",item.getMenuPath());
            map.put("component",item.getMenuComponent());
            list.add(map);
        }
        return Result.success(list);
    }


//    @PreAuthorize("hasAuthority('sys:prize:get')")
    @ApiOperation(value="获取未发货奖品列表", notes="根据商家id获取未发货奖品列表")
    @ApiImplicitParam(name = "businessId", value = "商家id", dataType = "int", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="成功"),
            @ApiResponse(code=401, message = "商家未发货订单列表为空"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/getOrderList")
    public PageInfo<BusinessOrder> getOrderList(Integer businessId,String receiver, String goodsName, String phone, String shipStatus, String orderId,
                                                         @RequestParam(defaultValue = "1") int current,
                                                         @RequestParam(defaultValue = "10") int size){
        List<BusinessOrder> businessOrders = businessService.getOrderList(businessId);
        if (!goodsName.isEmpty() || !phone.isEmpty() || !shipStatus.isEmpty() || !orderId.isEmpty() || !receiver.isEmpty()) {
            current = 1;
        }
        Predicate<BusinessOrder> predicate = businessOrder -> businessOrder.getGoods().getGoodName().contains(goodsName)&& //商品名称
                businessOrder.getOrderId().contains(orderId)&&  //订单号
                businessOrder.getUserAddress().getRecipientPhone().contains(phone)&& //收货手机号
                businessOrder.getShipStatus().contains(shipStatus)&& //发货状态
                businessOrder.getUserAddress().getRecipientName().contains(receiver); //收货人姓名

        List<BusinessOrder> result = businessOrders.stream()
                .filter(predicate)
                .collect(Collectors.toList());

        List<BusinessOrder> pageList = result.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<BusinessOrder> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = result.size();
        pageInfo. setTotal(total);
        return pageInfo;
    }


////    @PreAuthorize("hasAuthority('sys:prize:get')")
//    @ApiOperation(value="获取已发货奖品列表", notes="根据商家id获取已发货奖品列表")
//    @ApiImplicitParam(name = "businessId", value = "商家id", dataType = "int", paramType = "query")
//    @ApiResponses(value={
//            @ApiResponse(code=200, message="成功"),
//            @ApiResponse(code=401, message = "商家未已发货订单列表为空"),
//            @ApiResponse(code=500, message="服务器错误")
//    })
//    @GetMapping("/getPrizeListShipped")
//    public PageInfo<BusinessOrder> getPrizeListShipped(Integer businessId,String name,
//                                                         @RequestParam(defaultValue = "1") int current,
//                                                         @RequestParam(defaultValue = "10") int size){
//
//        List<BusinessOrder> businessOrders = businessService.getPrizeListShipped(businessId);
//        if (!name.isEmpty()) {
//            current = 1;
//        }
//        Predicate<BusinessOrder> predicate = businessOrder -> businessOrder.getGoods().getGoodName().contains(name)||
//                                                              businessOrder.getOrderId().contains(name)||
//                                                              businessOrder.getUserAddress().getRecipientPhone().contains(name)||
//                                                              businessOrder.getUserAddress().getRecipientName().contains(name);
//
//        List<BusinessOrder> result = businessOrders.stream()
//                .filter(predicate)
//                .collect(Collectors.toList());
//
//        List<BusinessOrder> pageList = result.stream()
//                .skip((current - 1) * size) // 跳过前面的记录
//                .limit(size) // 取出指定数量的记录
//                .collect(Collectors.toList()); // 将结果转换为列表
//        PageInfo<BusinessOrder> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
//        long total = result.size();
//        pageInfo. setTotal(total);
//        return pageInfo;
//
//    }
//    @PreAuthorize("hasAuthority('sys:order:get')")
    @ApiOperation(value="发货", notes="根据订单id发货")
    @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "int", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="发货成功"),
            @ApiResponse(code=401, message = "发货失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PutMapping("/ship")
    public Result ship(String orderId,String sendId, String company, String remarks){
        Integer result = businessService.ship(orderId, sendId, company, remarks);
        if(result != 0){
            return Result.success("发货成功");
        }else{
            return Result.error("401","发货失败");
        }
    }

    @ApiOperation(value="获取物流进度", notes="根据商家id获取未发货奖品列表")
    @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "int", paramType = "query")
    @GetMapping("/getProgressInfo")
    public Result getProgressInfo(String orderId){
        List<Progress> list=businessService.getProgressByOrderId(orderId);
        if(list!=null){
            return Result.success(list);
        }else{
            return Result.error("500","未能获取物流进度");
        }
    }

    @ApiOperation(value="获取销量数据", notes="根据商家id获取销量数据")
    @ApiImplicitParam(name = "businessId", value = "商家id", dataType = "int", paramType = "query")
    @GetMapping("/getStatistics")
    public Result getStatistics(Integer businessId){
        List<Map<String,Object>> res= businessService.getStatistics(businessId);
        System.out.println(res);
        if(res!=null){
            return Result.success(res);
        }else{
            return Result.error("500","获取数据失败");
        }
    }


    @ApiOperation(value="获取快递公司信息", notes="获取快递公司信息")
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取成功"),
            @ApiResponse(code=500, message="获取数据失败")
    })
    @GetMapping("/getLogisticsCompany")
    public Result getLogisticsCompany(){
        QueryWrapper<LogisticsCompany> queryWrapper = new QueryWrapper<>();
        List<LogisticsCompany> res = logisticsMapper.selectList(queryWrapper);
        if(!res.isEmpty()){
            return Result.success(res);
        }else {
            return Result.error("500","无公司信息");
        }
    }


    @ApiOperation(value="获取订单物流信息", notes="根据订单id获取订单物流信息")
    @ApiImplicitParam(name = "orderId", value = "订单id", dataType = "int", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取成功"),
            @ApiResponse(code=500, message="未能获取物流进度")
    })
    @GetMapping("/getLogisticsMsgByOrderId")
    public Result getLogisticsMsgByOrderId(String orderId){
        LogisticsMsg logisticsMsg = businessService.getLogisticsMsgByOrderId(orderId);
        if(logisticsMsg != null){
            return Result.success(logisticsMsg);
        }else{
            return Result.error("500","获取物流信息失败");
        }
    }

    @Resource
    private CommentService commentService;

    @PutMapping("/businessReplyComment")
    public Result businessReplyComment(Integer commentId, String reply,@RequestBody Map<String,String> obj, String date) throws ParseException {
        int result = commentService.businessReplyComment(commentId, reply, obj.get("image"), date);
        if(result == 1){
            return Result.success("商家回复成功");
        }else {
            return Result.error("500","商家回复失败");
        }
    }

    @DeleteMapping("/deleteComment")
    public Result deleteComment(Integer commentId){
        int result = commentService.deleteComment(commentId);
        if(result == 1){
            return Result.success("商家删除评价成功");
        }else {
            return Result.error("500","商家删除评论失败");
        }
    }



    @Resource
    private CommentMapper commentMapper;
    @GetMapping("/getCommentList")
    public PageInfo<Comment> getCommentList(Integer businessId, String startTime, String endTime, String goodName,
                                            Integer score,
                                             @RequestParam(defaultValue = "0")Integer ifHaveReply,
                                             @RequestParam(defaultValue = "1") int current,
                                             @RequestParam(defaultValue = "10") int size) throws ParseException {
        List<Comment> commentList = commentService.getCommentList(businessId,startTime,endTime,goodName,score,ifHaveReply);
        List<Comment> pageList = commentList.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<Comment> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = commentList.size();
        pageInfo. setTotal(total);
        return pageInfo;
    }

    @GetMapping("/getOrderComment")
    public Result getOrderComment(String orderId){
        Comment comment = commentService.getOrderComment(orderId);
        if(comment != null){
            return Result.success(comment);
        }else {
            return Result.error("500","获取订单评价失败");
        }
    }

    @Resource
    private ActivityService activityService;

    @ApiOperation(value="商家参与活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessId", value = "商家id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "activityId", value = "活动id", dataType = "int", paramType = "query"),
    })
    @ApiResponses(value={
            @ApiResponse(code=200, message="成功"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PostMapping("/joinActivity")
    public Result joinActivity(Integer businessId, Integer activityId){
        int res = activityService.joinActivity(businessId, activityId);
        if(res == 1){
            return Result.success("参与成功");
        }else {
            return Result.error("500","参与失败");
        }
    }

    @ApiOperation(value="商家退出活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessId", value = "商家id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "activityId", value = "活动id", dataType = "int", paramType = "query"),
    })
    @ApiResponses(value={
            @ApiResponse(code=200, message="成功"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PostMapping("/exitActivity")
    public Result exitActivity(Integer businessId, Integer activityId){
        int res = activityService.exitActivity(businessId, activityId);
        if(res == 1){
            return Result.success("退出成功");
        }else {
            return Result.error("500","退出失败");
        }
    }





    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private ActivityWhoJoinMapper activityWhoJoinMapper;
    //testOK
    //获取所有活动
//    //@PreAuthorize("hasAuthority('sys:activity:get')")
    @SneakyThrows
    @ApiOperation(value="商家获取活动列表", notes="根据活动名称、每页数量和当前页码获取活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "每页数量", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int", paramType = "query")
    })
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取活动列表成功"),
            @ApiResponse(code=400, message="获取活动列表失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/BusinessGetActivities")
    public PageInfo<ActivityBoolean> getActivities(String activityName, String startTime, String endTime, Integer businessId,
                                                           @RequestParam(defaultValue = "1") int current,
                                                           @RequestParam(defaultValue = "10") int size){
        List<Activity> activityList = new ArrayList<>();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        if(startTime != null && !startTime.isEmpty()){
            startDate = formatter.parse(startTime);
        }
        if(endTime != null && !endTime.isEmpty()){
            endDate = formatter.parse(endTime);
        }
        activityList = activityMapper.getActivitySearch(activityName,startDate,endDate);
        List<Activity> pageList = activityList.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表

        List<ActivityWhoJoin> activityWhoJoins = activityWhoJoinMapper.selectList(null);

        List<ActivityBoolean> pageMsg = new ArrayList<>();
        for(Activity activity : pageList){
            ActivityWhoJoin temp = new ActivityWhoJoin(businessId, activity.getActivityId());
            if(activityWhoJoins.contains(temp)){
                pageMsg.add(new ActivityBoolean(activity,true));
            }else {
               pageMsg.add(new ActivityBoolean(activity, false));
            }
        }
        PageInfo<ActivityBoolean> pageInfo = new PageInfo<>(pageMsg); // 构造 PageInfo 对象
        long total = pageMsg.size();
        pageInfo.setTotal(total);
        return pageInfo;




    }
}

